package com.pengpeng.rocketmq.web;

import com.pengpeng.rocketmq.consumer.OrderedConsumer;
import com.pengpeng.rocketmq.producer.OrderedProducer;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author 彭鹏 顺序消息
 * @date 2021/10/25.
 */
@Slf4j
@RestController
@RequestMapping("/ordered")
public class OrderedController {

    @Autowired
    private OrderedProducer producer;

    @RequestMapping("/orderedProducer")
    public Object orderedProducer() throws Exception {
        String[] tags = new String[] {"TagB", "TagC", "TagD", "TagE", "TagF"};
        for (int i = 1; i < 21; i++) {
            int orderId = i % 5;
            //Create a message instance, specifying topic, tag and message body.
            Message msg = new Message(OrderedConsumer.TOPIC, tags[i % tags.length], "KEY" + i,
                    ("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET));
            SendResult sendResult = producer.getProducer().send(msg, new MessageQueueSelector() {
                @Override
                public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
                    Integer id = (Integer) arg;
                    int index = id % mqs.size();
                    return mqs.get(index);
                }
            }, orderId);

            System.out.printf("%s%n", sendResult);
        }
        return "成功";
    }
}

